<?php

namespace Base;

use \Mapper\MemberModel as MemberMapper;

class ApiController extends \Yaf\Controller_Abstract {

    public function response($data, $status = true, $code = 200, $msg = null) {
        $callback = $this->getRequest()->get('callback', null);

        if(empty($callback)) {
            return $status ? \Response::data($data, $msg, $code) : \Response::error($data ? : $msg, $code);
        }

        $resource = [
            'status' => $status,
            'code'   => (int)$code,
            'msg'    => $msg,
        ];

        $resource['data'] = is_array($data)
            ? $data
            : ($data instanceof \Base\Model\AbstractModel ? $data->toArray() : (string)$data);

        return \Response::callback($resource, $callback);
    }

    public function getSession() {
        return \Yaf\Session::getInstance();
    }

    public function uid() {
        $uid = $this->getSession()->get('Uid');

        if(!isset($uid['uid']) || (int)$uid['uid'] < 65535) {
            $this->wxredirect(60000);
        }

        $memberMapper = MemberMapper::getInstance();
        $memberModel  = $memberMapper->findById($uid['uid']);

        if(!$memberModel instanceof \MemberModel) {
            $this->wxredirect(60000);
        }

        if(empty($memberModel->getMobile())) {
            $this->wxredirect(60001);
        }

        return $uid['uid'];
    }

    protected function wxredirect($code) {
        if(isset($_SERVER['HTTP_REFERER'])) {
            $this->getSession()->set('Referer', $_SERVER['HTTP_REFERER']);
        }

        $this->response(null, false, $code);
        exit();
    }
}
